package com.cngphone.AnFetion.Fetion.SIPC;

import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FrameWork;
import com.cngphone.AnFetion.Fetion.FetionBase;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive.IPackageReceivedHandler;
import com.cngphone.AnFetion.tools.LogUtil;

public abstract class SIPCBase extends FetionBase {
	private static final String TAG = "SIPCBase";
	
    protected static final String SIPC_COMMON_HEADER = "S fetion.com.cn SIP-C/2.0"; 
    protected SerialManager serialManager;
    protected TcpSendAndReceive connection;
    protected final static String SIPC_RESPONSE_CODE_INVITE_TRYING = "100";
    public final static String SIPC_RESPONSE_CODE_OK = "200";
    public final static String SIPC_RESPONSE_CODE_NOTEXIST = "404";
    protected final static String SIPC_RESPONSE_CODE_TEMPORARILYUNAVALIABLE = "480";
    protected final static String SIPC_RESPONSE_CODE_SENDSMS_OK = "280";
    protected final static String SIPC_RESPONSE_CODE_UNAUTHRIZED = "401";
    protected final static String SIPC_RESPONSE_CODE_NOSUBSCRIPTION = "522";

    public SIPCBase(SerialManager serialManager, TcpSendAndReceive connection) {
        this.serialManager = serialManager;
        this.connection = connection;
    }
    
    protected boolean SendAndReceiveResponse(final FetionSIPC sipc) {
    	LogUtil.d(TAG, "send and receive");
        return SendAndReceiveResponse(sipc, 10000);
    }

    protected boolean SendAndReceiveResponse(final FetionSIPC sipc, int timeout) {
        IPackageReceivedHandler handler = new IPackageReceivedHandler() {

            @Override
            public boolean received(FetionSIPC receivedsipc) {
                try {
                    if (receivedsipc.isResponse() && sipc.GetQ().equals(receivedsipc.GetQ())) {
                        sipc.SetResponse(receivedsipc);
                        LogUtil.d(TAG, "RCVD SIPC : " + receivedsipc.toString());
                        FrameWork.synchronizednotify(this);
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

        };
        connection.addPackageReceivedQueue(handler);
        connection.SendSIPC(sipc);
        LogUtil.d(TAG, "SEND SIPC : " + sipc.toString());
        if (sipc.response == null) {
            // System.out.println("wait " + sipc.response);
            FrameWork.synchronizedwait(handler, timeout);
            // System.out.println("ret " + sipc.response);
        }
        connection.removePackageReceivedQueue(handler);
        if (sipc.response != null) return true;
        else return false;
    }
}
